package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.team;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.DefaultEnum;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.jdbc.utils.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationDevice;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationEnum;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationFuncModelEnum;
import com.gzhryc.shared_device.oem.code.agent.dao.models.RelationUserDeviceCount;
import com.gzhryc.shared_device.oem.code.agent.dao.models.RelationUserFuncModelCount;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationDeviceService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationFuncModelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentRelationDeviceSearch;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentRelationSearch;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.dao.models.IncomeRatioContent;
import com.gzhryc.shared_device.oem.code.place.dao.models.UserProfitPlaceCount;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.mng.dto.team.TeamUserData;
import com.gzhryc.shared_device.oem.h5.agent.mng.dto.team.TeamUserPlace;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class UserController {

    @Route(value = { "/team/user/list.html" })
    public String list(HttpServletRequest request) {
        return "/team/user/list.html";
    }

    @Route(value = "/team/user/list.data")
    public ListResult<TeamUserData> listData(HttpServletRequest request) {
        ListResult<TeamUserData> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(loginUser != null) {
            AgentRelationSearch search = new AgentRelationSearch();
            search.setUserId(loginUser.getId());

            result.getBody().setTotal(AgentRelationService.self().countJoinBySearch(search));
            List<AgentRelation> agentRelationList = AgentRelationService.self().findJoinBySearch(search,pageNo,pageLimit);


            if(agentRelationList != null && agentRelationList.size() > 0){
                result.getBody().setData(new ArrayList<>());
                List<Long> userIds = new ArrayList<>();
                for(AgentRelation agentRelation : agentRelationList){
                    userIds.add(agentRelation.getRelationUserId());
                }

                List<RelationUserDeviceCount> userDeviceCountList = AgentRelationDeviceService.self()
                        .findDeviceCountByUserKeys(loginUser.getId(),userIds);

                List<UserProfitPlaceCount> placeCountList = PlaceProfitUserService.self().findPlaceCountByUserKeys(loginUser.getId()
                        ,userIds);

                List<RelationUserFuncModelCount> funcModelCountList = AgentRelationFuncModelService.self().findFuncModelCountByUserKeys(loginUser.getId()
                		,userIds);

                for(AgentRelation agentRelation : agentRelationList){
                    TeamUserData item = new TeamUserData();
                    item.setId(agentRelation.getRelationUser().getId());
                    item.setName(agentRelation.getRelationUser().getName());
                    item.setNickname(agentRelation.getRelationUser().getNickname());
                    item.setPhone(agentRelation.getRelationUser().getPhone());
                    item.setSex(agentRelation.getRelationUser().getSex());
                    item.setSexName(agentRelation.getRelationUser().getSexName());
                    item.setRoleType(agentRelation.getRoleType());
                    item.setRoleTypeName(agentRelation.getRoleTypeName());
                    item.setNote(agentRelation.getNote());
                    item.setCreateDate(agentRelation.getCreateDate());
                    if(userDeviceCountList != null && userDeviceCountList.size() > 0){
                        for(RelationUserDeviceCount userDeviceCount : userDeviceCountList){
                            if(item.getId().equals(userDeviceCount.getRelationUserId())){
                                item.setDeviceCount(userDeviceCount.getDeviceCount());
                                break;
                            }
                        }
                    }
                    
                    if(placeCountList != null && placeCountList.size() > 0){
                        for(UserProfitPlaceCount placeCount : placeCountList){
                            if(item.getId().equals(placeCount.getUserId())){
                                item.setPlaceCount(placeCount.getPlaceCount());
                                break;
                            }
                        }
                    }
                    
                    if(funcModelCountList != null && funcModelCountList.size() > 0){
                        for(RelationUserFuncModelCount userProfitPlaceCount : funcModelCountList){
                            if(item.getId().equals(userProfitPlaceCount.getRelationUserId())){
                                item.setFuncModelCount(userProfitPlaceCount.getFuncModelCount());
                                break;
                            }
                        }
                    }

                    result.getBody().getData().add(item);
                }
            }
            if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        }
        return result;
    }

    @Route(value = { "/team/user/add.html" })
    public String add(HttpServletRequest request) {
        request.setAttribute("sexList", DefaultEnum.Sex.values());
        request.setAttribute("roleTypeList", AgentRelationEnum.RoleType.values());
        return "/team/user/edit.html";
    }

    @Route(value = { "/team/user/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        User user = WebUtils.getParameter(request,User.class);
        Integer roleType = WebUtils.getInteger(request,"roleType");
        String note = WebUtils.getString(request,"note");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(loginUser != null && roleType != null && user != null && StringTools.isNotBlank(user.getPhone())){
            User temp = UserService.self().getByPhone(user.getPhone());
            if(temp != null){
            	AgentRelation agentRelation = new AgentRelation();
                agentRelation.setUserId(loginUser.getId());
                agentRelation.setRelationUserId(temp.getId());
                agentRelation.setRoleType(roleType);
                agentRelation.setNote(note);
                
                try {
                    if(AgentRelationService.self().add(agentRelation,null)){
                        result.setCode(DtoConstants.SUCCESS,null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }else{
                AgentRelation agentRelation = new AgentRelation();
                agentRelation.setUserId(loginUser.getId());
                agentRelation.setRoleType(roleType);
                agentRelation.setNote(note);
                
                try {
                    if(AgentRelationService.self().add(agentRelation,user,null)){
                        result.setCode(DtoConstants.SUCCESS,null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }
        }
        return result;
    }

    @Route(value = { "/team/user/info.html" })
    public String info(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(id != null && loginUser != null) {
            AgentRelation agentRelation = AgentRelationService.self().getJoinByKeys(loginUser.getId(),id);
            WebUtils.setAttribute(request, agentRelation);
            
            AgentRelationDeviceSearch search1 = new AgentRelationDeviceSearch();
        	search1.setUserId(agentRelation.getUserId());
        	search1.setRelationUserId(agentRelation.getRelationUserId());
        	Long deviceCount = AgentRelationDeviceService.self().countJoinBySearch(search1);
        	request.setAttribute("deviceCount", deviceCount);
        	
            Long placeCount = PlaceProfitUserService.self().countByUserKeys(agentRelation.getUserId()
            		,agentRelation.getRelationUserId());
          	request.setAttribute("placeCount", placeCount);
        }
        return "/team/user/info.html";
    }

    @Route(value = "/team/user/device/list.data")
    public ListResult<AgentRelationDevice> deviceListData(HttpServletRequest request) {
        ListResult<AgentRelationDevice> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        if(relationUserId != null && loginUser != null) {
	        List<AgentRelationDevice> data = AgentRelationDeviceService.self().findJoinByUserKeys(loginUser.getId(),relationUserId);
	        if(data != null && data.size() > 0){
	            result.setCode(DtoConstants.SUCCESS, null);
	            result.getBody().setData(data);
	        }
        }
        return result;
    }
	
	@Route(value = "/team/user/place/list.data")
    public ListResult<TeamUserPlace> placeListData(HttpServletRequest request) {
        ListResult<TeamUserPlace> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        if(relationUserId != null && loginUser != null) {
	        List<PlaceProfitUser> data = PlaceProfitUserService.self().findByUserKeys(loginUser.getId(),relationUserId);
	        if(data != null && data.size() > 0){
	        	result.setCode(DtoConstants.SUCCESS, null);
	        	result.getBody().setData(new ArrayList<>());
	        	List<Long> placeIds = new ArrayList<>();
	        	for(PlaceProfitUser profitUser : data) {
	        		placeIds.add(profitUser.getPlaceId());
	        	}
	        	List<PlacePhysicalStore> placeList = PlacePhysicalStoreService.self().findByIds(placeIds);
	            
	        	for(PlaceProfitUser profitUser : data) {
	        		TeamUserPlace item = new TeamUserPlace();
	        		item.setId(profitUser.getPlaceId());
	        		item.setRoleTypeName(profitUser.getRoleTypeName());
	        		item.setCreateDate(profitUser.getCreateDate());
	        		
	        		item.setIncomeRatioNote("未配置分成");
	        		if(StringTools.isNotBlank(profitUser.getIncomeRatioContent())) {
	        			IncomeRatioContent incomeRatioContent = JsonTools.fromJson(profitUser.getIncomeRatioContent(), IncomeRatioContent.class);
	        			if(incomeRatioContent != null && incomeRatioContent.getItems() != null && incomeRatioContent.getItems().size() > 0) {
	        				String temp = "";
	        				for(IncomeRatioContent.Item incomeRatioItem : incomeRatioContent.getItems()) {
	        					temp = temp + "," + EBusinessType.note(incomeRatioItem.getBusinessType()) + ":" + incomeRatioItem.getIncomeRatio()+"%";
	        				}
	        				item.setIncomeRatioNote(temp.substring(1));
	        			}
	        		}
	        		
	        		if(placeList != null && placeList.size() > 0) {
	        			for(PlacePhysicalStore place : placeList) {
	        				if(place.getId().equals(item.getId())) {
	        					item.setName(place.getName());
	        					item.setAreaName(place.getAreaName());
	        					item.setTypeNames(place.getTypeNames());
	        					break;
	        				}
	        			}
	        		}
	        		result.getBody().getData().add(item);
	        	}
	        }
        }
        return result;
    }

	@Route(value = {"/team/user/role_type/update.html"})
	public String updateRoleType(HttpServletRequest request) {
		User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        if(relationUserId != null && loginUser != null) {
	        AgentRelation agentRelation = AgentRelationService.self().getJoinByKeys(loginUser.getId(), relationUserId);
	        if(agentRelation != null) {
	        	WebUtils.setAttribute(request, agentRelation);
	        }
        }
        request.setAttribute("roleTypeList", AgentRelationEnum.RoleType.values());
        return "/team/user/edit_role_type.html";
    }
    
    @Route(value = { "/agent/relation/user/role_type/update.do" })
    public AjaxResult doUpdateRoleType(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败，请稍后再试");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        Integer roleType = WebUtils.getInteger(request, "roleType");
        if(relationUserId != null && loginUser != null && roleType != null) {
	        try {
	            if(AgentRelationService.self().updateRoleType(loginUser.getId(),relationUserId,roleType)){
	                result.setCode(DtoConstants.SUCCESS,null);
	            }
	        } catch (LogicException e) {
	            result.setMsg(e.getMessage());
	        }
        }
        return result;
    }
    
    @Route(value = {"/team/user/pwd/update.html"})
    public String updatePwd(HttpServletRequest request) {
        return "/team/user/pwd.html";
    }

    @Route(value = { "/team/user/pwd/update.do" })
    public AjaxResult doUpdatePwd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        Long userId = WebUtils.getLong(request, "userId");
        String newPwd1 = WebUtils.getString(request, "newPwd1");
        String newPwd2 = WebUtils.getString(request, "newPwd2");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (userId != null && loginUser != null) {
            if (StringTools.isNotBlank(newPwd1) && StringTools.isNotBlank(newPwd2) && newPwd1.equals(newPwd2)) {
                if (ValidateTools.checkPwd(newPwd1)) {
                    AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),userId);
                    if(agentRelation != null) {
                        try {
                            if (UserService.self().updateLoginPwd(userId, newPwd1)) {
                                result.setCode(DtoConstants.SUCCESS, null);
                            }
                        } catch (LogicException e) {
                            result.setMsg(e.getMessage());
                        }
                    }
                } else {
                    result.setMsg("密码过于简单，请重新设置");
                }
            }
        }
        return result;
    }

    @Route(value = "/team/user/busi_config/list.data")
    public ListResult<AgentRelationBusinessConfig> busiConfigListData(HttpServletRequest request) {
        ListResult<AgentRelationBusinessConfig> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        if(relationUserId != null && loginUser != null) {
	        List<AgentRelationBusinessConfig> data = AgentRelationBusinessConfigService.self().findByUserKeys(loginUser.getId(),relationUserId);
	        if(data != null && data.size() > 0){
	            result.setCode(DtoConstants.SUCCESS, null);
	            result.getBody().setData(data);
	        }
        }
        return result;
    } 
    
    @Route(value = "/team/user/func_model/list.data")
    public ListResult<AgentRelationFuncModel> funcModelListData(HttpServletRequest request) {
        ListResult<AgentRelationFuncModel> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        if(relationUserId != null && loginUser != null) {
	        List<AgentRelationFuncModel> data = AgentRelationFuncModelService.self().findJoinByUserKeys(loginUser.getId(),relationUserId);
	        if(data != null && data.size() > 0){
	        	String resDomain = PropertyTools.get().getString("resDomain");
	        	for(AgentRelationFuncModel item : data) {
	        		if(StringTools.isNotBlank(item.getFuncModel().getIconUrl())) {
	        			item.getFuncModel().setIconUrl(WebUtils.setHttpDomain(resDomain, item.getFuncModel().getIconUrl()));
	        		}
	        	}
	            result.setCode(DtoConstants.SUCCESS, null);
	            result.getBody().setData(data);
	        }
        }
        return result;
    }

    @Route(value = { "/team/user/func_model/add.html" })
    public String addFuncModel(HttpServletRequest request) {
    	User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        if(relationUserId != null && loginUser != null) {
        	AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(), relationUserId);
        	request.setAttribute("type", agentRelation.getRoleType());
        }
        return "/team/user/func_model/edit.html";
    }

    @Route(value = { "/team/user/func_model/add.do" })
    public AjaxResult doAddFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        AgentRelationFuncModel funcModel = WebUtils.getParameter(request, AgentRelationFuncModel.class);
        if(loginUser != null && funcModel != null && funcModel.getRelationUserId() != null && funcModel.getFuncModelId() != null) {
	        try {
	        	funcModel.setUserId(loginUser.getId());
	        	funcModel.setState(AgentRelationFuncModelEnum.State.Open.index());		//默认开启
	            if(AgentRelationFuncModelService.self().add(funcModel)){
	                result.setCode(DtoConstants.SUCCESS,null);
	            }
	        } catch (LogicException e) {
	            result.setMsg(e.getMessage());
	        }
        }
        return result;
    }

    @Route(value = { "/team/user/func_model/del.do" })
    public AjaxResult doDelFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        Long funcModelId = WebUtils.getLong(request,"funcModelId");
        if(relationUserId != null && loginUser != null && funcModelId != null) {
	        try {
	            if(AgentRelationFuncModelService.self().deleteByKeys(loginUser.getId(),relationUserId,funcModelId)){
	                result.setCode(DtoConstants.SUCCESS,null);
	            }
	        } catch (LogicException e) {
	            result.setMsg(e.getMessage());
	        }
        }
        return result;
    }
    
    @Route(value = { "/team/user/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long id = WebUtils.getLong(request,"id");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(id != null && loginUser != null) {
            try {
                if (AgentRelationService.self().deleteByKeys(loginUser.getId(),id)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route("/team/user/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        Long total = 0L;
        if(loginUser != null) {
            AgentRelationSearch search = new AgentRelationSearch();
            search.setUserId(loginUser.getId());
            search.setTrim(term);
            total = AgentRelationService.self().countJoinBySearch(search);

            List<AgentRelation> agentRelationList = AgentRelationService.self().findJoinBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
            if(agentRelationList != null && agentRelationList.size() > 0){
                for (AgentRelation agentRelation : agentRelationList) {
                    SelectResult.Item item = new SelectResult.Item();
                    item.setId(agentRelation.getRelationUserId().toString());
                    item.setText(agentRelation.getRelationUser().getName() + "("+agentRelation.getRelationUser().getPhone()+")");
                    result.getBody().getData().add(item);
                }
            }
        }
        result.getBody().setPage(pageNo);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }
}
